<template>
  <div class="flow-up">
    <div class="add-flow flex items-center" v-if="!followUpValue">
      <div class="head">
        <el-image class="w-100% h-100%" :src="avatar"></el-image>
      </div>
      <div class="input" @click="addFollow">写跟进...</div>
    </div>
    <!-- add -->
    <div class="create-follow flex justify-start" v-else>
      <div class="head"><el-image class="w-100% h-100%" :src="avatar"></el-image></div>
      <div class="mix-content">
        <el-form
          ref="formRef"
          v-loading="formLoading"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="跟进类型" prop="type">
                <el-select v-model="formData.type" placeholder="请选择跟进类型">
                  <el-option
                    v-for="dict in followOptionsList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
                <el-button class="ml-10px" type="primary" @click="goToAddFollowType"
                  >新 增</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下次联系时间" prop="nextTime">
                <el-date-picker
                  v-model="formData.nextTime"
                  placeholder="选择下次联系时间"
                  type="date"
                  value-format="x"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="跟进内容" prop="content">
                <el-input
                  v-model="formData.content"
                  :rows="3"
                  type="textarea"
                  placeholder="请输入跟进内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="图片" prop="picUrls">
                <UploadImgs v-model="formData.picUrls" width="100px" height="100px" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="附件" prop="fileUrls">
                <UploadFile v-model="formData.fileUrls" class="min-w-80px" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="formData.bizType == BizTypeEnum.CRM_CUSTOMER">
              <el-form-item label="关联联系人" prop="contactIds">
                <el-button @click="handleOpenContact">
                  <Icon class="mr-5px" icon="ep:plus" />
                  添加联系人
                </el-button>
                <FollowUpRecordContactForm :contacts="formData.contacts" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="formData.bizType == BizTypeEnum.CRM_CUSTOMER">
              <el-form-item label="关联商机" prop="businessIds">
                <el-button @click="handleOpenBusiness">
                  <Icon class="mr-5px" icon="ep:plus" />
                  添加商机
                </el-button>
                <FollowUpRecordBusinessForm :businesses="formData.businesses" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="mix-btn pl-120px">
          <el-button type="primary" class="bgc4" @click="submitForm">发布</el-button>
          <el-button @click="followUpValue = false">取消</el-button>
        </div>
      </div>
    </div>
    <div class="flow-title flex justify-between items-center">
      <div class="flow-left flex items-center"
        ><span class="w-42px">显示: </span
        ><el-button style="background-color: #344563; color: #fff; border: none"
          >跟进记录</el-button
        >
      </div>
      <div class="flow-right">
        <el-popover placement="bottom" :visible="visible" :width="200" trigger="click">
          <template #reference>
            <el-button
              @click="visible = true"
              style="background-color: #ebecf0; color: #42526e; border: none"
            >
              <el-icon><Filter /></el-icon>
              筛选</el-button
            >
          </template>
          <div class="mb-10px" style="font-size: 14px; color: #42526e"> 跟进类型 </div>
          <el-select v-model="queryParams.type" placeholder="请选择" @change="selectFollowType">
            <el-option
              v-for="item in followupOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <div class="mt-20px flex justify-end">
            <el-button @click="visible = false">取消</el-button>
            <el-button
              style="background-color: #344563; border: none; color: #fff"
              @click="filterData"
              >确定</el-button
            >
          </div>
        </el-popover>
      </div>
    </div>
    <!-- list -->
    <div class="flow-list mt-20px" style="border-radius: 4px">
      <div
        v-for="activity in processedList"
        class="flex pt-8px pb-5px"
        :key="activity.id"
        style="background-color: #f4f5f7"
      >
        <div class="" style="flex: 0 0 100px">
          <div v-if="activity.isShow" class="w-100%">
            <div
              class="w-100% text-24px color-#172b4d text-center h-31px"
              style="line-height: 31px"
            >
              {{ getDay(activity.createTime) }}
            </div>
            <div class="color-#172b4d text-14px text-center">
              {{ getYear(activity.createTime) }}
              {{ getMonth(activity.createTime) }}
            </div>
          </div>
        </div>
        <div class="flex-1 flex" style="flex-direction: column">
          <div class="text-14px color-#172b4d flex items-center">
            <span>{{ activity.creatorName }}</span>
            <div
              class="ml-16px color-#0052cc bg-#e6eefa text-12px pl-9px pr-9px h-24px flex items-center"
              style="border-radius: 4px"
              >{{ crmType[bizType] }}跟进记录</div
            >
          </div>
          <div class="color-#6b778c mt-2px text-14px">
            {{ formatDate(activity.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </div>
          <div class="color-#172b4d text-14px mt-8px">{{ activity.content }}</div>
          <div class="flex items-center justify-between mt-8px">
            <div
              class="text-12px text-[var(--secondary-text-color)] flex justify-left items-center"
            >
              <span class="mr-10px color-#172b4d" v-if="activity.type == 0">系统外呼</span>
              <span :class="activity.typeName ? 'mr-10px' : ''" class="color-#172b4d" v-else>{{
                activity.typeName
              }}</span>
              <el-tag
                type="warning"
                class="mr-10px"
                size="small"
                v-if="activity.type == 1 && !activity.callStatus"
                >未接通</el-tag
              >
              <span
                >下次联系时间：{{ activity.nextTime ? formatDate(activity.nextTime) : '' }}</span
              >
            </div>
          </div>
          <div
            class="mt-15px"
            style="display: flex; justify-content: space-between; align-items: center"
            v-if="activity.callLogId && activity.callRecordUrl"
          >
            <AudioPlayers :url="activity.callRecordUrl" />
            <div style="cursor: pointer" @click="showDiag(activity)">
              <el-tooltip content="语音转文字" placement="bottom" effect="light">
                <svg
                  t="1726627027730"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="6218"
                  width="24"
                  height="24"
                >
                  <path
                    d="M833.79 322.4H713.67a22.69 22.69 0 0 0-17.95 17.95c-2.44 12.41 5.54 24.38 17.95 26.81h121c34.79 0.22 62.94 28.37 63.16 63.16v421.29c0 35.24-28.59 63.61-63.6 63.61H412.49c-35.24-0.22-63.38-29.03-63.16-64.04V686.31c-1.77-9.08-8.87-15.96-17.95-17.95-12.41-2.44-24.38 5.54-27.04 17.95v164.88c0 60.06 48.76 108.81 108.81 108.81h420.41c60.06 0 108.81-48.75 108.81-108.81V430.34c-0.21-59.84-48.97-107.94-108.58-107.94z"
                    p-id="6219"
                  ></path>
                  <path
                    d="M751.35 855.17V526.29c-1.11-7.09-6.87-12.86-13.96-13.96-9.31-1.55-17.95 4.65-19.5 13.96v327.55c0.22 9.08 7.54 16.4 16.62 16.62 8.41 0 15.95-6.64 16.84-15.29zM633 805.08c9.31 0 16.84-7.32 17.06-16.62V593c-1.11-7.09-6.87-12.86-13.96-13.96-9.31-1.55-18.17 4.65-19.5 13.96v195.47c0 9.08 7.32 16.17 16.4 16.61zM845.75 739.49v-97.73c-1.11-7.32-6.87-12.86-13.96-13.96-9.31-1.55-17.95 4.87-19.5 13.96v97.73c0.22 9.08 7.54 16.4 16.62 16.62 9.09 0 16.62-7.32 16.84-16.62zM295.48 343.02h88.87l-44.32-87.99zM518.21 641.98v97.73c0.22 9.08 7.54 16.4 16.62 16.62 9.31 0 16.84-7.32 17.06-16.62v-97.73c0.22-1.77 0.22-3.77 0-5.54-1.55-9.31-10.19-15.51-19.5-13.96-9.31 1.32-15.74 10.19-14.18 19.5z"
                    p-id="6220"
                  ></path>
                  <path
                    d="M598.43 505.9v-367c0-41.44-33.46-74.9-74.91-74.9H156.53c-41.44 0-74.91 33.46-74.91 74.9v366.55c0 41.44 33.46 74.9 74.91 74.9h366.55c41.44 0.24 75.13-33 75.35-74.45z m-121.89-38.34c-3.55 1.77-7.54 2.66-11.75 2.66-9.97 1.11-19.72-3.99-24.6-12.63l-30.58-64.04H269.77l-32.36 64.04c-4.21 13.52-18.62 20.83-31.91 16.62-13.52-4.21-20.83-18.62-16.62-31.91 0.89-2.66 2.22-5.32 3.77-7.54l124.1-247.32c7.76-12.41 24.16-16.18 36.35-8.42 3.32 2.22 6.21 5.1 8.42 8.42L487.4 434.32c5.98 12.41 1.11 26.82-10.86 33.24z"
                    p-id="6221"
                  ></path>
                </svg>
              </el-tooltip>
            </div>
          </div>
          <!-- 附件图片列表 -- 开始 -->
          <div v-if="activity.picUrls">
            <el-image
              style="width: 50px; height: 50px"
              :src="url"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              fit="cover"
              v-for="(url, index) in activity.picUrls"
              :key="'url' + index"
              :initial-index="index"
              :preview-src-list="activity.picUrls"
            />
          </div>
          <!-- 附件文件列表 -- 开始 -->
          <div v-if="activity.fileUrls">
            <span
              class="mb-10px block flex justify-between rd-2px bg-#eFF3F650 p-8px"
              v-for="(url, index) in activity.fileUrls"
              :key="'url' + index"
            >
              <span>附件</span>
              <el-link :icon="Download" :href="url"></el-link>
            </span>
          </div>
          <!-- 关联联系人  开始 -->
          <div
            class="text-12px text-[var(--secondary-text-color)]"
            v-if="bizType === BizTypeEnum.CRM_CUSTOMER && activity.contacts.length"
            >关联联系人：<el-link
              v-for="contact in activity.contacts"
              :key="`key-${contact.id}`"
              :underline="false"
              type="primary"
              @click="openContactDetail(contact.id)"
              class="ml-5px"
            >
              {{ contact.name }}
            </el-link></div
          >
          <!-- 关联商机 开始 -->
          <div
            v-if="activity.businesses.length"
            class="mt-10px text-12px text-[var(--secondary-text-color)]"
            >关联商机：<el-link
              v-for="business in activity.businesses"
              :key="`key-${business.id}`"
              :underline="false"
              type="primary"
              @click="openBusinessDetail(business.id)"
              class="ml-5px"
            >
              {{ business.name }}
            </el-link></div
          >
        </div>
        <div class="del" style="flex: 0 0 50px">
          <el-tooltip class="box-item" effect="dark" content="点击可复制跟进内容" placement="top">
            <el-icon
              @click="copyContent(activity.content)"
              class="icon-copy"
              style="cursor: pointer"
              size="16px"
              color="#172b4d"
              ><CopyDocument
            /></el-icon>
          </el-tooltip>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <el-icon style="cursor: pointer" class="ml-10px"><MoreFilled /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="delFlow(activity.id)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="color-#0052cc text-14px text-center mt-10px" style="cursor: pointer" v-if="!isMore">
      <div @click="pageNext">
        <div>加载更多</div>
        <svg
          t="1742280566606"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="1500"
          width="20"
          height="20"
        >
          <path
            d="M794.819048 502.247619c9.752381 9.752381 9.752381 29.257143 0 39.009524l-258.438096 234.057143c-4.87619 4.87619-14.628571 9.752381-19.504762 9.752381-9.752381 0-14.628571-4.87619-19.504761-9.752381l-258.438096-234.057143c-4.87619-4.87619-9.752381-9.752381-9.752381-19.504762s4.87619-14.628571 9.752381-19.504762c14.628571-9.752381 29.257143-9.752381 43.885715 0l234.057142 214.552381 238.933334-214.552381c9.752381-9.752381 29.257143-9.752381 39.009524 0z m-9.752381-248.685714c9.752381 9.752381 9.752381 29.257143 0 39.009524l-258.438096 234.057142c-4.87619 4.87619-14.628571 9.752381-19.504761 9.752381-9.752381 0-14.628571-4.87619-19.504762-9.752381L229.180952 287.695238c-4.87619-4.87619-9.752381-9.752381-9.752381-19.504762s4.87619-14.628571 9.752381-19.504762c14.628571-9.752381 29.257143-9.752381 43.885715 0l234.057143 214.552381 234.057142-214.552381c14.628571-9.752381 29.257143-9.752381 43.885715 4.876191z"
            fill="#0052cc"
            p-id="1501"
          ></path>
        </svg>
      </div>
    </div>
    <div class="color-#6b778c text-14px text-center mt-10px" v-else>没有更多数据了</div>
  </div>
  <!-- 弹窗 -->
  <ContactListModal
    ref="contactTableSelectRef"
    :customer-id="formData.bizId"
    @success="handleAddContact"
    :is-width="false"
  />
  <BusinessListModal
    ref="businessTableSelectRef"
    :customer-id="formData.bizId"
    @success="handleAddBusiness"
    :is-width="false"
  />
  <!-- 详情 -->
  <DetailDes ref="detailRef" />
</template>

<script setup lang="ts">
import DetailDes from '@/views/call/record/detail.vue'
import { Filter, CopyDocument, MoreFilled } from '@element-plus/icons-vue'
import avatarImg from '@/assets/imgs/avatar.gif'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { FollowUpRecordApi, FollowUpRecordVO } from '@/api/crm/followup'
import { BizTypeEnum } from '@/api/crm/permission'
import FollowUpRecordBusinessForm from '@/views/crm/followup/components/FollowUpRecordBusinessForm.vue'
import FollowUpRecordContactForm from '@/views/crm/followup/components/FollowUpRecordContactForm.vue'
import BusinessListModal from '@/views/crm/business/components/BusinessListModal.vue'
import * as BusinessApi from '@/api/crm/business'
import ContactListModal from '@/views/crm/contact/components/ContactListModal.vue'
import * as ContactApi from '@/api/crm/contact'
import { getFollowTypeConfigList } from '@/api/crm/module/index'
import router from '@/router'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { formatDate } from '@/utils/public'

defineOptions({ name: 'FollowUpRecordForm' })

const crmType = {
  1: '线索',
  2: '客户',
  3: '联系人',
  4: '商机',
  5: '合同',
  6: '产品',
  7: '回款',
  8: '回款计划'
}

const { wsCache } = useCache()
const user = wsCache.get(CACHE_KEY.USER)
const avatar = user.user.avatar ? user.user.avatar : avatarImg

const props = defineProps({
  clueValue: Object,
  bizType: String
})
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  bizType: '',
  bizId: '',
  type: ''
})
const { t } = useI18n()
const message = useMessage()
const followUpValue = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formData = ref({
  bizType: undefined,
  bizId: -1,
  bizIdList: [],
  businesses: [],
  contacts: []
})
const followupOption = ref([
  {
    name: '全部',
    id: ''
  },
  {
    name: '系统外呼',
    id: '0'
  }
])
const visible = ref(false)
const filterData = () => {
  queryParams.pageNo = 1
  getList()
  visible.value = false
}
const formRules = reactive({
  type: [{ required: true, message: '跟进类型不能为空', trigger: 'change' }],
  content: [{ required: true, message: '跟进内容不能为空', trigger: 'blur' }],
  nextTime: [{ required: true, message: '下次联系时间不能为空', trigger: 'blur' }]
})
/**年*/
const getYear = (timestamp) => {
  const date = new Date(timestamp)
  return date.getFullYear()
}

// 获取月份
const getMonth = (timestamp) => {
  const date = new Date(timestamp)
  return String(date.getMonth() + 1).padStart(2, '0')
}

// 获取日期
const getDay = (timestamp) => {
  const date = new Date(timestamp)
  return String(date.getDate()).padStart(2, '0')
}
const detailRef = ref(null)
/*显示语音转文字组件*/
const showDiag = (item) => {
  detailRef.value.open(item.callLogId)
}
/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
  formData.value.businesses = []
  formData.value.contacts = []
  formData.value.bizIdList = []
}
const loading = ref(false)
const list = ref([])
const total = ref(false)
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleDateString()
}
const processedList = computed(() => {
  // 首先对数组按createTime进行排序
  const sortedList = list.value
  // 遍历数组并设置isShow属性
  return sortedList.map((item, index, arr) => {
    const currentDate = formatDate(item.createTime)
    const prevDate = index > 0 ? formatDate(arr[index - 1].createTime) : null
    return {
      ...item,
      isShow: currentDate !== prevDate
    }
  })
})
const isMore = computed(() => {
  if (list.value.length != total.value) {
    return false
  } else {
    return true
  }
})
/**下一页*/
const pageNext = async () => {
  queryParams.pageNo += 1
  loading.value = true
  try {
    const data = await FollowUpRecordApi.getFollowUpRecordPage(queryParams)
    data.list.map((item) => {
      list.value.push(item)
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FollowUpRecordApi.getFollowUpRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const formRef = ref() // 表单 Ref
const createType = ref('')
const followOptionsList = ref([])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      contactIds: formData.value.contacts.map((item) => item.id),
      businessIds: formData.value.businesses.map((item) => item.id)
    }
    if (createType.value == 'batch') {
      await FollowUpRecordApi.createBatchFollowUpRecord(data)
    } else {
      await FollowUpRecordApi.createFollowUpRecord(data)
    }
    message.success(t('common.createSuccess'))
    followUpValue.value = false
    getList()
    // 发送操作成功的事件
  } finally {
    formLoading.value = false
  }
}
const addFollow = () => {
  formData.value.businesses = []
  formData.value.contacts = []
  formData.value.bizIdList = []
  formData.value.type = ''
  formData.value.nextTime = ''
  formData.value.content = ''
  followUpValue.value = true
}
const openContactDetail = (id: number) => {
  router.push({ name: 'CrmContactDetail', params: { id } })
}

/** 打开商机详情 */
const openBusinessDetail = (id: number) => {
  router.push({ name: 'CrmBusinessDetail', params: { id } })
}
const getFollowList = async () => {
  const data = await getFollowTypeConfigList({ moduleId: formData.value.moduleId })
  followOptionsList.value = data
  followupOption.value = [...followupOption.value, ...data]
}
watch(
  () => [props.clueValue, props.bizType],
  ([val, val2]) => {
    if (Object.keys(val).length && val2) {
      resetForm()
      formData.value.bizId = val.id
      formData.value.moduleId = val.moduleId
      formData.value.bizType = val2
      queryParams.pageNo = 1
      queryParams.bizType = val2
      queryParams.bizId = val.id
      createType.value = 'only'
      getList()
      getFollowList()
    }
  },
  { deep: true, immediate: true }
)
/** 关联联系人 */
const contactTableSelectRef = ref()
const handleOpenContact = () => {
  contactTableSelectRef.value?.open()
}
const handleAddContact = (contactId: [], newContacts: ContactApi.ContactVO[]) => {
  newContacts.forEach((contact) => {
    if (!formData.value.contacts.some((item) => item.id === contact.id)) {
      formData.value.contacts.push(contact)
    }
  })
}

/** 关联商机 */
const businessTableSelectRef = ref()
const handleOpenBusiness = () => {
  businessTableSelectRef.value?.open()
}
const handleAddBusiness = (businessId, newBusinesses: BusinessApi.BusinessVO[]) => {
  newBusinesses.forEach((business) => {
    if (!formData.value.businesses.some((item) => item.id === business.id)) {
      formData.value.businesses.push(business)
    }
  })
}

const goToAddFollowType = () => {
  router.push({
    path: '/crm/module'
  })
}
/**复制*/
const copyContent = (txt) => {
  navigator.clipboard
    .writeText(txt)
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch((err) => {
      ElMessage.error('无法复制文本: ', err)
    })
}
/**删除*/
const delFlow = (id) => {
  ElMessageBox.confirm('确定要删除当前数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const data = await FollowUpRecordApi.deleteFollowUpRecord(id)
      if (data) ElMessage.success('删除成功!')
      queryParams.pageNo = 1
      getList()
    })
    .catch(() => {})
}
</script>

<style lang="scss" scoped>
.flow-up {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #172b4d1a;
  margin: 0 8px;
  padding: 16px;
  .add-flow {
    .head {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: #dfe1e6;
      color: #172b4d;
      font-size: 14;
      margin-right: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .input {
      width: calc(100% - 90px);
      padding: 0 24px;
      height: 38px;
      border: 1px solid #dfe1e6;
      border-radius: 4px;
      font-size: 14px;
      color: #7a869a;
      line-height: 38px;
    }
  }
  .create-follow {
    .head {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: #dfe1e6;
      color: #172b4d;
      font-size: 14;
      margin-right: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .mix-content {
      flex: 1;
      border: 1px solid #dfe1e6;
      border-radius: 4px;
      padding: 20px 16px 24px 8px;
    }
  }
}
.bgc4 {
  background-color: #0052cc;
}
.flow-title {
  margin-top: 40px;
  .flow-left {
    font-size: 14px;
    color: #172b4d;
  }
}
.icon-copy:hover {
  color: #0052cc;
}
</style>
